import React, { useState, useEffect } from "react"
import { Menu } from "antd"
import {
  AppstoreOutlined,
  MailOutlined,
  SettingOutlined,
} from "@ant-design/icons"

import { request } from "../api/request"

const { SubMenu } = Menu

const LongitudinalMenu = ({
  setMenuData,
  MenuMode = "inline",
  url = "",
  data = [],
}) => {
  const [icons, setIcons] = useState({
    AppstoreOutlined: <AppstoreOutlined />,
  })
  const [menuInfo, setMenuInfo] = useState({ menus: [], menusIndex: {} })
  const [requestFlag, setRequestFlag] = useState(true)
  const handleClick = ({ key }) => {
    setMenuData({ api: menuInfo["menusIndex"][key]["api"], en_name: key })
  }
  useEffect(() => {
    if (requestFlag && url !== '') {
      request
        .get({
          url: url,
          data: data,
        })
        .then((res) => {
          setMenuInfo(res)
        })
        .catch((err) => {
          setMenuInfo({ menus: [], menusIndex: {} })
        })
      setRequestFlag(false)
    }
  })

  let renderMenu = (data) => {
    if (data) {
      return data.map((item) => {
        if (item["children"].length > 0) {
          return (
            <SubMenu
              key={item["en_name"]}
              icon={icons[item["icon"]]}
              title={item["name"]}
            >
              {renderMenu(item["children"])}
            </SubMenu>
          )
        }
        return (
          <Menu.Item key={item["en_name"]} icon={icons[item["icon"]]}>
            {item["name"]}
          </Menu.Item>
        )
      })
    }
  }

  return (
    <Menu
      mode={MenuMode}
      // theme={theme}
      onSelect={handleClick}
    >
      {renderMenu(menuInfo["menus"])}
    </Menu>
  )
}

export default LongitudinalMenu
